#!/bin/bash

# 加密货币信息聚合系统部署脚本
# Crypto Aggregator Deployment Script

set -e

echo "🚀 开始部署加密货币信息聚合系统..."

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 函数：打印彩色消息
print_message() {
    echo -e "${2}${1}${NC}"
}

# 函数：检查命令是否存在
check_command() {
    if ! command -v $1 &> /dev/null; then
        print_message "错误: $1 未安装" $RED
        exit 1
    fi
}

# 函数：检查Node.js版本
check_node_version() {
    NODE_VERSION=$(node --version | cut -d'v' -f2)
    REQUIRED_VERSION="16.0.0"
    
    if [ "$(printf '%s\n' "$REQUIRED_VERSION" "$NODE_VERSION" | sort -V | head -n1)" != "$REQUIRED_VERSION" ]; then
        print_message "错误: Node.js版本需要 >= $REQUIRED_VERSION，当前版本: $NODE_VERSION" $RED
        exit 1
    fi
    
    print_message "✓ Node.js版本检查通过: $NODE_VERSION" $GREEN
}

# 函数：安装依赖
install_dependencies() {
    print_message "📦 安装项目依赖..." $BLUE
    
    if [ -f "package-lock.json" ]; then
        npm ci
    else
        npm install
    fi
    
    print_message "✓ 依赖安装完成" $GREEN
}

# 函数：创建必要的目录
create_directories() {
    print_message "📁 创建必要的目录..." $BLUE
    
    mkdir -p data/json
    mkdir -p data/exports
    mkdir -p logs
    
    print_message "✓ 目录创建完成" $GREEN
}

# 函数：复制配置文件
setup_config() {
    print_message "⚙️ 设置配置文件..." $BLUE
    
    if [ ! -f "src/config/config.js" ]; then
        if [ -f "src/config/config.example.js" ]; then
            cp src/config/config.example.js src/config/config.js
            print_message "✓ 配置文件已从示例复制" $GREEN
            print_message "⚠️ 请编辑 src/config/config.js 添加您的API密钥" $YELLOW
        else
            print_message "错误: 找不到配置文件示例" $RED
            exit 1
        fi
    else
        print_message "✓ 配置文件已存在" $GREEN
    fi
}

# 函数：运行测试
run_tests() {
    print_message "🧪 运行测试..." $BLUE
    
    # 启动测试服务器
    timeout 10s node src/test-app.js &
    TEST_PID=$!
    
    sleep 3
    
    # 测试API端点
    if curl -f http://localhost:3000/api/health > /dev/null 2>&1; then
        print_message "✓ API健康检查通过" $GREEN
    else
        print_message "⚠️ API健康检查失败，但这可能是正常的" $YELLOW
    fi
    
    # 停止测试服务器
    kill $TEST_PID 2>/dev/null || true
    wait $TEST_PID 2>/dev/null || true
}

# 函数：设置PM2
setup_pm2() {
    print_message "🔧 设置PM2进程管理..." $BLUE
    
    if ! command -v pm2 &> /dev/null; then
        print_message "安装PM2..." $BLUE
        npm install -g pm2
    fi
    
    # 创建PM2配置文件
    cat > ecosystem.config.js << EOF
module.exports = {
  apps: [{
    name: 'crypto-aggregator',
    script: 'src/app.js',
    instances: 1,
    autorestart: true,
    watch: false,
    max_memory_restart: '1G',
    env: {
      NODE_ENV: 'production',
      PORT: 3000
    },
    error_file: './logs/pm2-error.log',
    out_file: './logs/pm2-out.log',
    log_file: './logs/pm2-combined.log',
    time: true
  }]
};
EOF
    
    print_message "✓ PM2配置完成" $GREEN
}

# 函数：创建systemd服务
setup_systemd() {
    print_message "🔧 设置systemd服务..." $BLUE
    
    SERVICE_FILE="/etc/systemd/system/crypto-aggregator.service"
    CURRENT_DIR=$(pwd)
    CURRENT_USER=$(whoami)
    
    sudo tee $SERVICE_FILE > /dev/null << EOF
[Unit]
Description=Crypto Aggregator Service
After=network.target

[Service]
Type=simple
User=$CURRENT_USER
WorkingDirectory=$CURRENT_DIR
ExecStart=/usr/bin/node src/app.js
Restart=always
RestartSec=10
Environment=NODE_ENV=production
Environment=PORT=3000

[Install]
WantedBy=multi-user.target
EOF
    
    sudo systemctl daemon-reload
    sudo systemctl enable crypto-aggregator
    
    print_message "✓ systemd服务设置完成" $GREEN
}

# 函数：创建Docker配置
setup_docker() {
    print_message "🐳 创建Docker配置..." $BLUE
    
    # Dockerfile
    cat > Dockerfile << EOF
FROM node:16-alpine

# 设置工作目录
WORKDIR /app

# 复制package文件
COPY package*.json ./

# 安装依赖
RUN npm ci --only=production

# 复制源代码
COPY . .

# 创建必要的目录
RUN mkdir -p data/json data/exports logs

# 暴露端口
EXPOSE 3000

# 健康检查
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD curl -f http://localhost:3000/api/health || exit 1

# 启动应用
CMD ["node", "src/app.js"]
EOF

    # docker-compose.yml
    cat > docker-compose.yml << EOF
version: '3.8'

services:
  crypto-aggregator:
    build: .
    ports:
      - "3000:3000"
    environment:
      - NODE_ENV=production
      - PORT=3000
    volumes:
      - ./data:/app/data
      - ./logs:/app/logs
      - ./src/config/config.js:/app/src/config/config.js
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:3000/api/health"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 40s

volumes:
  data:
  logs:
EOF

    # .dockerignore
    cat > .dockerignore << EOF
node_modules
npm-debug.log
.git
.gitignore
README.md
.env
.nyc_output
coverage
.nyc_output
.coverage
.coverage/
logs/
data/
*.log
EOF

    print_message "✓ Docker配置创建完成" $GREEN
}

# 函数：显示部署信息
show_deployment_info() {
    print_message "\n🎉 部署完成！" $GREEN
    print_message "\n📋 部署信息:" $BLUE
    print_message "• 项目目录: $(pwd)" $NC
    print_message "• Web界面: http://localhost:3000" $NC
    print_message "• API文档: http://localhost:3000/api" $NC
    print_message "• 配置文件: src/config/config.js" $NC
    print_message "• 日志目录: logs/" $NC
    print_message "• 数据目录: data/" $NC
    
    print_message "\n🚀 启动命令:" $BLUE
    print_message "• 开发模式: npm run dev 或 node src/test-app.js" $NC
    print_message "• 生产模式: npm start 或 node src/app.js" $NC
    print_message "• PM2管理: pm2 start ecosystem.config.js" $NC
    print_message "• systemd: sudo systemctl start crypto-aggregator" $NC
    print_message "• Docker: docker-compose up -d" $NC
    
    print_message "\n⚠️ 重要提醒:" $YELLOW
    print_message "1. 请编辑 src/config/config.js 添加您的API密钥" $NC
    print_message "2. 首次运行建议使用测试模式验证功能" $NC
    print_message "3. 生产环境请确保API密钥的安全性" $NC
    print_message "4. 定期备份data目录中的数据" $NC
}

# 主函数
main() {
    print_message "🔍 检查系统环境..." $BLUE
    
    # 检查必要的命令
    check_command "node"
    check_command "npm"
    check_command "curl"
    
    # 检查Node.js版本
    check_node_version
    
    # 解析命令行参数
    SETUP_PM2=false
    SETUP_SYSTEMD=false
    SETUP_DOCKER=false
    RUN_TESTS=false
    
    while [[ $# -gt 0 ]]; do
        case $1 in
            --pm2)
                SETUP_PM2=true
                shift
                ;;
            --systemd)
                SETUP_SYSTEMD=true
                shift
                ;;
            --docker)
                SETUP_DOCKER=true
                shift
                ;;
            --test)
                RUN_TESTS=true
                shift
                ;;
            --all)
                SETUP_PM2=true
                SETUP_DOCKER=true
                RUN_TESTS=true
                shift
                ;;
            -h|--help)
                echo "用法: $0 [选项]"
                echo "选项:"
                echo "  --pm2      设置PM2进程管理"
                echo "  --systemd  设置systemd服务"
                echo "  --docker   创建Docker配置"
                echo "  --test     运行测试"
                echo "  --all      执行所有设置"
                echo "  -h, --help 显示帮助信息"
                exit 0
                ;;
            *)
                print_message "未知选项: $1" $RED
                exit 1
                ;;
        esac
    done
    
    # 执行部署步骤
    install_dependencies
    create_directories
    setup_config
    
    if [ "$RUN_TESTS" = true ]; then
        run_tests
    fi
    
    if [ "$SETUP_PM2" = true ]; then
        setup_pm2
    fi
    
    if [ "$SETUP_SYSTEMD" = true ]; then
        setup_systemd
    fi
    
    if [ "$SETUP_DOCKER" = true ]; then
        setup_docker
    fi
    
    show_deployment_info
}

# 运行主函数
main "$@"

